package com.pinc.exam;

import android.database.Cursor;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

public class Library_Add extends WidgetActivity {
	private ListView lv;
	private DBClass dbHelper;
	private Cursor mCursor;
	private Question_Adapter mAdapter;
	private long mCatgrID;
	private long mGroupID;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_layout);

		mCatgrID = getIntent().getLongExtra("id", 0);
		mGroupID = getIntent().getLongExtra("group_id", 0);

		dbHelper = new DBClass(this);

		initWidget();

		showQuestion();

		//lv.setOnItemClickListener(new ItemClickListener());
	}

	private void showQuestion()
	{
		mAdapter = new Question_Adapter(this, Question_Adapter.MODE_INSERT);
		mCursor = dbHelper.getQuestionsNotInGroup(mGroupID, mCatgrID);

		if (mCursor.moveToFirst())
		{
			do{
				Question_Class qc = new Question_Class(
						mCursor.getInt(mCursor.getColumnIndex("_id")),
						mCursor.getInt(mCursor.getColumnIndex("_id")),
						mCursor.getString(mCursor.getColumnIndex(DBClass.COL_QLIB_QUESTION)),
						mCursor.getInt(mCursor.getColumnIndex(DBClass.COL_QLIB_BINGO_NO)),
						mCursor.getInt(mCursor.getColumnIndex(DBClass.COL_QLIB_TESTED_NO)),
						mCursor.getFloat(mCursor.getColumnIndex(DBClass.COL_QLIB_CREDIT))
				);
				mAdapter.add(qc);
			}while(mCursor.moveToNext());
		}
		mCursor.close();
		dbHelper.mDB.close();

		lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		lv.setAdapter(mAdapter);
	}

	@Override
	protected void initWidget() {
		super.initWidget();

		/* set upbar */
		tv_title.setText(getIntent().getStringExtra("title"));

		b_next.setText(getResources().getString(R.string.str_finish));
		b_next.setVisibility(View.VISIBLE);
		b_next.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				addQuestions();
				finish();
			}
		});

		b_prev.setText(getResources().getString(R.string.str_cancel));
		b_prev.setVisibility(View.VISIBLE);
		b_prev.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		lv = (ListView) this.findViewById(R.id.listView1);
	}

	private void addQuestions()
	{
		SparseBooleanArray boolarr = lv.getCheckedItemPositions();
		ListAdapter adapter = lv.getAdapter();
		for ( int i=0; i<lv.getCount(); i++)
		{
			if ( boolarr.get(i))
				dbHelper.addQuestion2Group(mGroupID, adapter.getItemId(i));
		}
	}
}
